<?php

declare(strict_types=1);

namespace App\Controller\Home\User;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Order;
use App\Model\Service;
use App\Model\Station;
use App\Services\AlipayService;
use App\Services\Iot\IotService1 as IotService;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Qiniu\Http\Request;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class UserDeviceController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**设备详情
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function detail(RequestInterface $request):ResponseInterface{
        $sn = $request->input('sn');
        $sn = trim($sn);
        if(!$sn){
            return $this->error(1001,'设备不存在');
        }
        $data = $this->device->where('sn',$sn)
            ->first(['id','sn','channel','port_status','last_online_at','station_id','is_refund',
                'charge_id','inline','signal','is_active','sp_full_empty','is_service']);
        if(!$data){
            return $this->error(1001,'设备不存在');
        }
        try{
            if(empty($data->port_status)){
                $status = [];
                for($channelNumber = 1; $channelNumber <= $data->channel; $channelNumber ++) {
                    $status[] = [
                        'number' => $channelNumber,
                        'status' => 4,
                    ];
                }
                $data->port_status = $status;
            }
        }catch (\Exception $e){
            $status = [];
            for($channelNumber = 1; $channelNumber <= $data->channel; $channelNumber ++) {
                $status[] = [
                    'number' => $channelNumber,
                    'status' => 4,
                ];
            }
            $data->port_status  = $status;
        }
        $data['station'] = $this->station->where('id',$data['station_id'])
            ->first(['id','name','address','distributor_id','lat','lng']);
        return $this->success($data);
    }


    /**获取设备号套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getCharge(RequestInterface $request):ResponseInterface{
        $sn =$request->input('sn',0,'int');
        $sn = trim($sn);
        if(!$sn){
            return $this->error(1001,'设备不存在');
        }
        $chargeId = $this->device->where('sn',$sn)->value('charge_id');
        if($chargeId <= 0){
            $charge = $this->chargeOption->where('distributor_id',0)
                ->where('is_del',1)->first();
        }else{
            $charge = $this->chargeOption->where('id',$chargeId)->first();
        }
        if(!$charge){
            return $this->error(1001,'设备暂无可用套餐');
        }
        $charge['sp_full_empty'] = $this->device->where('sn',$sn)->value('sp_full_empty');
        if($charge->type == 3){
            $charge['elec_children'] =  ChargeDetail::where('charge_option_id',$charge['id'])
                ->where('type',ChargeDetail::ELEC_TYPE)
                ->orderBy('sort','desc')->get()->toArray();
            $charge['service_children'] =  ChargeDetail::where('charge_option_id',$charge['id'])
                ->where('type',ChargeDetail::SERVICE_TYPE)
                ->orderBy('sort','desc')->get()->toArray();
        }else{
            $charge['power_children'] = ChargeDetail::where('charge_option_id',$charge['id'])
                ->where('type',ChargeDetail::POWER_TYPE)
                ->orderBy('sort','desc')->get()->toArray();
            $charge['time_children'] = ChargeDetail::where('charge_option_id',$charge['id'])
                ->where('type',ChargeDetail::TIME_TYPE)
                ->orderBy('sort','desc')->get()->toArray();
        }
        return $this->success($charge);
    }

    /**获取客服电话和二维码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getService(RequestInterface $request):ResponseInterface{
        $station_id = $request->input('station_id');
        if(!$station_id){
            return $this->error();
        }
        $distributor_id = $this->station->where('id',$station_id)->value('distributor_id');
        $distributor = $this->distributors->where('id',$distributor_id)->first(['customer_service_phone','service_image']);
        return $this->success($distributor);
    }


    /**服务列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function serviceList(RequestInterface $request):ResponseInterface
    {
        $data['list'] = Service::orderBy('days', 'desc')
            ->get()->toArray();
        $data['total']= Service::count();
        return $this->success($data);
    }


    /**二维码重定向
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function qrCodeParse(RequestInterface $request){
        $sn = $request->input('sn');
//        $uri = AlipayService::getRedirect($sn);
//        if($uri['alipay_open_mini_qrcode_bind_response']['code'] != 10000){
//            return $response->json('操作繁忙 请稍后再试');
//        }
        $sn = trim($sn);
        $response = container()->get(\Hyperf\HttpServer\Contract\ResponseInterface::class);
        $url = Common::MAIN_HOST.'/sub/pages/equipment-detail-user/index/?sn='.$sn;
        return $response->redirect($url);
    }


}
